<template>
  <div class="clearfix">
    <a-upload
      v-model:file-list="fileList"
      :action="action"
      :showUploadList="{
        showRemoveIcon: !disabled,
      }"
      accept=".jpg,.jpeg,.png"
      list-type="picture-card"
      :headers="{
        token: token,
      }"
      @change="imgChange"
      @remove="imgRemove"
    >
      <div v-if="fileList!.length < limit && !disabled">
        <plus-outlined />
        <div style="margin-top: 8px">上传</div>
      </div>
    </a-upload>
  </div>
</template>
<script setup lang="ts">
import type { UploadProps, UploadChangeParam } from "ant-design-vue";
import { ref, watch, onMounted, getCurrentInstance } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { config } from "../config";
const token = window.localStorage.getItem("token");
const fileList = ref<UploadProps["fileList"]>([]);
const props = defineProps({
  imgList: {
    type: Array,
  },
  limit: {
    type: Number,
    default: 9,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["update:imgList", "imgChange"]);
const getImgs = (): Array<string | undefined> | undefined => {
  const imgs = fileList.value;
  const doneImg = imgs?.filter((it) => it.status == "done");
  return doneImg
    ?.map((it) => {
      if (it.url) {
        return it.url;
      }
      if (it.response) {
        const temp = it.response as any;
        return temp.data.url || temp.data;
      }
    })
    .filter((it) => !!it);
};
const imgChange = (val: UploadChangeParam) => {
  const { file, fileList } = val;
  if (file.status == "done") {
    emits("update:imgList", getImgs() || []);
    emits("imgChange", getImgs() || []);
  }
};
const setImgList = () => {
  if (props.imgList && props.imgList?.length > 0) {
    fileList.value = props.imgList?.map((it, index) => {
      return {
        uid: `-${index}`,
        name: `image.png`,
        status: "done",
        url: it as string,
      };
    });
  }
};

const imgRemove = () => {
  setTimeout(() => {
    emits("update:imgList", getImgs() || []);
    emits("imgChange", getImgs() || []);
  }, 0);
};
watch(
  () => props.imgList,
  (nv) => {
    setImgList();
  },
  {
    deep: true,
    immediate: true,
  }
);
const action = ref("");
onMounted(() => {
  action.value =
    config.uploadUrl || "https://s.youdi.net/router/upload/save/file";
});
</script>
<script lang="ts">
export default {
  name: "x-upload",
};
</script>
<style lang="scss" scoped>
.box {
  color: #60d659;
}
</style>
